/*
 * Copyright 2011 android-jar-fixer authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.perunlabs.tool.fixandroidjar;

import java.io.IOException;
import java.io.PrintWriter;

import org.objectweb.asm.ClassAdapter;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.util.CheckClassAdapter;
import org.objectweb.asm.util.TraceClassVisitor;

public class Transformer {
  /**
   * Transforms the class bytecode by
   * <ul>
   * <li>removing 'throws new RuntimeExceptions("Stub!")' from constructors and
   * methods</li>
   * <li>adding private no-argument constructors if there's no such constructor</li>
   * <li>transforming methods to return default values for primitives types (for numbers - zero, for
   * booleans - false), null for class types</li>
   * </ul>
   */
  public static byte[] transform(byte[] originalBytecode, boolean trace) throws IOException {
    ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    ClassVisitor check = new CheckClassAdapter(classWriter);
    if (trace) {
      check = new TraceClassVisitor(check, new PrintWriter(System.out));
    }
    ClassAdapter classAdapter = new FixClassClassAdapter(check);
    ClassReader classReader = new ClassReader(originalBytecode);

    classReader.accept(classAdapter, 0);
    return classWriter.toByteArray();
  }
}
